package leetcode.每日一题;

import org.junit.Test;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ：zsy
 * @date ：Created 2022/11/2 8:14 PM
 * @description：
 */
public class LRU缓存 {
    @Test
    public void test() {
        /**
         * ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
         * [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
         *
         * 来源：力扣（LeetCode）
         * 链接：https://leetcode.cn/problems/lru-cache
         * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
         */
        LRUCache lruCache = new LRUCache(2);
        lruCache.put(1, 1);
        lruCache.put(2, 2);
        System.out.println(lruCache.get(1));
        lruCache.put(3, 3);
        System.out.println(lruCache.get(2));
        lruCache.put(4, 4);
        System.out.println(lruCache.get(1));
        System.out.println(lruCache.get(3));
        System.out.println(lruCache.get(4));
    }


    class LRUCache extends LinkedHashMap<Integer, Integer>{

        private final int CACHE_SIZE;

        public LRUCache(int capacity) {
            super((int)Math.ceil(capacity / 0.75f) + 1, 0.75f, true);
            this.CACHE_SIZE = capacity;
        }

        public int get(int key) {
            if (!super.containsKey(key)) {
                return -1;
            }
            return super.get(key);
        }

        public void put(int key, int value) {
            super.put(key, value);
        }


        @Override
        protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            return size() > CACHE_SIZE;
        }
    }

}
